<script setup lang="ts">
import { ref,onMounted,watch } from 'vue';
import type { SearchEmpModel, EmpExprModel, PaginationParam, EmpModelArray, DeptModelArray, EmpModel } from "@/api/model/model"
import { queryPageApi,addApi } from "@/api/emp"
import {queryAllApi as queryAllDeptsApi} from '@/api/dept';
import { ElMessage, type FormInstance, type FormRules, type UploadProps } from 'element-plus'

// 用来封装搜索框数据
const searchEmp = ref<SearchEmpModel>({
  name: '',
  gender: '',
  begin: '',
  end: '',
  date: []
})

// 侦听date属性值（单个对象属性值），并给begin和end重新赋值
watch(()=>searchEmp.value.date, (newVal, oldVal)=>{
  if(newVal) {
    searchEmp.value.begin = newVal[0]
    searchEmp.value.end = newVal[1]
  }else{
    searchEmp.value.begin = ''
    searchEmp.value.end = ''
  }
})

// 分页条件查询
const pageQuery = async ()=>{
  // 1.调用API发送异步请求
  const result = await queryPageApi(searchEmp.value.begin, searchEmp.value.end, searchEmp.value.gender, 
  searchEmp.value.name, pagination.value.currentPage, pagination.value.pageSize);
  // 2.获取响应数据并展示
  if(result.code) {
    empList.value = result.data.rows;           //分页结果集
    pagination.value.total = result.data.total; //总条数
  }
}

// 用来展示列表数据
const empList = ref<EmpModelArray>([])
const pagination = ref<PaginationParam>({
  currentPage: 1, //当前页码
  pageSize: 5,    //每页记录数
  total: 0        //总条数
})

// 每页记录数发生变化时触发的函数
const handleSizeChange = (pageSize: number) => {
  console.log(`每页记录数：${pageSize}`)
  pagination.value.pageSize = pageSize;
  pageQuery();
}
// 当前页码发生变化时触发的函数
const handleCurrentChange = (page: number) => {
  console.log(`当前页码: ${page}`)
  pagination.value.currentPage = page;
  pageQuery();
}

// 钩子函数
onMounted(()=>{
  pageQuery();
  queryAllDepts();
})

// 清空按钮触发函数
const clean = () => {
  // 将搜索框初始化
  searchEmp.value = {  
    name: '',
    gender: '',
    begin: '',
    end: '',
    date: []
  }
  pageQuery();
}

// 点击新增员工的时候，需要弹出对话框，并且清空历史对话框
const add = () => {
  dialogFormVisible.value = true;
  emp.value = {
    username: '',
    password: '',
    name: '',
    gender: '',
    phone: '',
    job: '',
    salary: '',
    image: '',
    entryDate: '',
    deptId: '',
    exprList: []
  }
  // 重置表单校验规则
  resetForm(empFormRef.value);
}

// 当复选框变化的时候会触发该函数
const multipleSelection = ref<EmpModel[]>([])
const handleSelectionChange = (val: EmpModel[]) => {
  multipleSelection.value = val
  console.log(val);
}

// -------------------------------新增员工------------------------------
const dialogFormVisible = ref<boolean>(false);
// 用来封装表单数据
const emp = ref<EmpModel>({
  username: '',
  password: '',
  name: '',
  gender: '',
  phone: '',
  job: '',
  salary: '',
  image: '',
  entryDate: '',
  deptId: '',
  exprList: []
})
const labelWidth = ref<number>(80)

//职位列表数据
const jobs = ref([{ name: '班主任', value: 1 },{ name: '讲师', value: 2 },{ name: '学工主管', value: 3 },{ name: '教研主管', value: 4 },{ name: '咨询师', value: 5 },{ name: '其他', value: 6 }])

//性别列表数据
const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }])

// 查询部门列表数据
const deptList = ref<DeptModelArray>([])

// 文件上传
// 文件上传成功之后会触发的函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (response,uploadFile) => {
  // console.log(response);
  // console.log(uploadFile);
  emp.value.image = response.data;
}

// 文件上传前会触发的函数----一般定义校验逻辑
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('文件格式不正确！')
    return false    //返回false，代表不上传
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('文件大小不能超过2MB!')
    return false
  }
  return true
}

// 当点击添加工作经历按钮时，触发该函数
const addWorkItem = () =>{
  // 往emp.exprList数组中添加数据
  emp.value.exprList.push({
    exprDate: [],
    begin: '',
    end: '',
    company: '',
    job: ''
  });
}

// 侦听emp对象(深度侦听)，一旦emp发生变化，就遍历emp.exprList，如果有值，则将exprDate里的元素赋值给begin和end
watch(emp, (newVal, oldVal)=>{
  if(emp.value.exprList) {
    emp.value.exprList.forEach((expr)=>{
      expr.begin = expr.exprDate[0];
      expr.end = expr.exprDate[1];
    })
  }
}, {deep: true})

// 当点击删除工作经历按钮时，触发该函数
const deleteWorkItem = (expr: EmpExprModel) => {
  // 获取元素在数组中的位置
  const start =  emp.value.exprList.indexOf(expr);
  console.log("start:"+start);
  
  if(start != -1) {
    // 从数组中删除指定位置的元素
    emp.value.exprList.splice(start, 1);
  }
}
const queryAllDepts = async () => {
  const result =await queryAllDeptsApi();
  deptList.value = result.data
}

// 保存员工数据
const save = async (formEl: FormInstance | undefined)=>{
  // 先校验表单是否合法
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {    //如果为true，代表校验成功，执行业务逻辑
      // 1.发送异步请求，调用后端的新增接口
      const result = await addApi(emp.value);
      // 2.如果保存成功，关闭对话框，刷新页面
      if(result.code) {
        ElMessage.success('操作成功！');
        dialogFormVisible.value = false;
        pageQuery();
      }else{
        ElMessage.success(result.msg);
      }
    }
  })
}

//表单校验规则
const empFormRef = ref<FormInstance>()
const rules = ref<FormRules<EmpModel>>({
  username: [
    { required: true, message: '用户名为必填项', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度为2-20个字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '姓名为必填项', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度为2-10个字', trigger: 'blur' }
  ],
  gender: [{ required: true, message: '性别为必填项', trigger: 'change' }],
  phone: [
    { required: true, message: '手机号为必填项', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/g, message: '请输入合法的手机号', trigger: 'blur' }
  ],
  salary: [
    { pattern: /^[1-9]\d*$/g, message: '请输入合法的数字', trigger: 'blur' }
  ]
})
// 重置表单校验规则
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// -------------------------------watch()演示------------------------------
// const a = ref<string>('') //数据源
// watch(a, (newVal, oldVal)=>{  //只要a数据源发生变化，就会触发该回调函数
//   console.log(`监听a发生变化，newVal：${newVal}, oldVal: ${oldVal}`);
// })

// 侦听对象--单个属性值
// watch(()=>searchEmp.value.name, (newVal, oldVal)=>{  //只要searchEmp的那么属性值发生变化，就会触发该回调函数
//   console.log(`监听a发生变化，newVal：${newVal}, oldVal: ${oldVal}`);
// })

// 侦听对象--全部属性值--需要深度侦听设置第三个参数（可选参数）deep--设置为true代表深度侦听； immediate-->设置为true回调函数会立即执行一次
// watch(searchEmp, (newVal, oldVal)=>{  //只要searchEmp的属性值发生变化，就会触发该回调函数
//   console.log(`监听a发生变化，${searchEmp.value.date}`);
// }, {deep: true, immediate: true})
</script>

<template>
  <h1>员工管理</h1> <br>
  <!-- 搜索框 -->
  <el-form :inline="true" :model="searchEmp" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="searchEmp.name" placeholder="请输入姓名"/>
    </el-form-item>

    <el-form-item label="性别">
      <el-select style="width: 80px;" v-model="searchEmp.gender" placeholder="请选择">
        <el-option label="男" value="1" />
        <el-option label="女" value="2" />
      </el-select>
    </el-form-item>

    <el-form-item label="入职时间">
      <el-date-picker
        v-model="searchEmp.date"
        type="daterange"
        range-separator="到"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="pageQuery">查询</el-button>
      <el-button @click="clean">清空</el-button>
    </el-form-item>
  </el-form>

  <!-- 功能按钮 -->
  <el-button type="success" @click="add">+ 新增员工</el-button>
  <el-button type="danger" @click="">- 批量删除</el-button>
  <br><br>

  <!-- 列表展示 -->
  <el-table :data="empList" border style="width: 100%" fit @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="name" label="姓名" align="center" width="130px" />
    <el-table-column label="性别" align="center" width="100px">
      <template #default="scope">
        {{ scope.row.gender == 1 ? '男' : '女' }}
      </template>
    </el-table-column>
    <el-table-column label="头像" align="center">
      <template #default="scope">
        <img :src="scope.row.image" width="50px">
      </template>
    </el-table-column>
    <el-table-column prop="deptName" label="所属部门" align="center" />
    <el-table-column label="职位" align="center" width="100px">
      <template #default="scope">
        <span v-if="scope.row.job == 1">班主任</span>
        <span v-else-if="scope.row.job == 2">讲师</span>
        <span v-else-if="scope.row.job == 3">学工主管</span>
        <span v-else-if="scope.row.job == 4">教研主管</span>
        <span v-else-if="scope.row.job == 5">咨询师</span>
        <span v-else>其他</span>
      </template>
    </el-table-column>
    <el-table-column prop="entryDate" label="入职时间" align="center" width="130px" />
    <el-table-column prop="updateTime" label="最后修改时间" align="center" />
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" size="small" @click="">编辑</el-button>
        <el-button type="danger" size="small" @click="">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <br>

  <!-- 分页组件Pagination -->
  <el-pagination
    v-model:current-page="pagination.currentPage"
    v-model:page-size="pagination.pageSize"
    :page-sizes="[5, 10, 20, 50, 100]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="pagination.total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />

  <!-- 新增员工 / 修改员工的 DiaLog对话框 -->
  <el-dialog v-model="dialogFormVisible" title="新增员工">
    <el-form :model="emp" :rules="rules" ref="empFormRef">
      <!-- 第一行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名" :label-width="labelWidth" prop="username">
            <el-input v-model="emp.username" placeholder="请输入用户名，2-20位" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" :label-width="labelWidth" prop="name">
            <el-input v-model="emp.name" placeholder="请输入姓名，2-10位"/>
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 第二行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="性别" :label-width="labelWidth" prop="gender">
            <el-select v-model="emp.gender" placeholder="请选择" style="width: 100%;">
              <!-- <el-option label="男" value="1" />
              <el-option label="女" value="2" /> -->
              <!-- 循环遍历genders列表 -->
              <el-option v-for="gender in genders" :key="gender.value" :label="gender.name" :value="gender.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" :label-width="labelWidth" prop="phone">
            <el-input v-model="emp.phone" placeholder="请输入合法的手机号" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="薪资" :label-width="labelWidth" prop="salary">
            <el-input v-model="emp.salary" placeholder="请输入纯数字的薪资" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期" :label-width="labelWidth">
            <el-date-picker v-model="emp.entryDate" type="date" placeholder="请选择入职日期" value-format="YYYY-MM-DD" style="width: 100%;"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属部门" :label-width="labelWidth">
            <el-select v-model="emp.deptId" placeholder="请选择" style="width: 100%;">
              <el-option v-for="(dept, index) in deptList" :key="index" :label="dept.name" :value="dept.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职位" :label-width="labelWidth">
            <el-select v-model="emp.job" placeholder="请选择" style="width: 100%;">
              <el-option v-for="(job, index) in jobs" :key="index" :label="job.name" :value="job.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row>
        <el-col :span="12">
          
        </el-col>
      </el-row>

      <!-- 第六行 -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="工作经历" :label-width="labelWidth">
            <el-button type="success" size="small" @click="addWorkItem">+ 添加工作经历</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第七行 -->
      <el-row :gutter="5" v-for="(expr, index) in emp.exprList" :key="index">
        <el-col :span="10">
          <el-form-item label="时间" size="small" :label-width="labelWidth">
            <el-date-picker v-model="expr.exprDate" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD"/>
          </el-form-item>
        </el-col>
        
        <el-col :span="6">
          <el-form-item label="公司" size="small">
            <el-input placeholder="公司名称" v-model="expr.company"/>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="职位" size="small">
            <el-input v-model="expr.job" placeholder="职位名称"/>
          </el-form-item>
        </el-col>

        <el-col :span="2">
          <el-form-item size="small">
            <el-button type="danger" @click="deleteWorkItem(expr)">- 删除</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save(empFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  border: 1px dashed; /* 添加边框 */
}
</style>